﻿<?
	
	error_reporting(E_ERROR);
	session_start();
	header ('Content-type: text/html; charset=utf-8');   
	require_once "../db/connection.inc"; 
	include_once "JSON.php";
	$action = $_REQUEST["action"];
	
	$json = new Services_JSON();
	 
	if("$action"=="list"){
		$start = $_REQUEST["start"] ;
		$end = $_REQUEST["limit"]  ;
		if("$start"=="") $start=0;
		if("$end"=="") $end=20;
		
		$sort = $_REQUEST["sort"];
		$direction = $_REQUEST["dir"];
		
		if($_REQUEST["vc__COGNOMENOM"]!="")  $_REQUEST["vc__COGNOMENOM"] = '*'.$_REQUEST["vc__COGNOMENOM"].'*';
		if($_REQUEST["vc__DEFUNTO"]!="")  $_REQUEST["vc__DEFUNTO"] = '*'.$_REQUEST["vc__DEFUNTO"].'*';
		if($_REQUEST["vc__POSIZIONE"]!="")  $_REQUEST["vc__POSIZIONE"] = '*'.$_REQUEST["vc__POSIZIONE"].'*';
		
		
		if("$sort"=="") {
			$sort = 'COGNOMENOM';
			$direction='';
		}	
			
			
		$sql = "
			SELECT schede.*,
			(select count(*) from schede where paganti.ID = schede.IDPAGANTE) as TOTSCHEDE,  
			(select DESCRIZION  from cimiteri where cimiteri.ID = schede.IDCIMITERO) as DESCCIMITERO,	
			(select concat(ID ,concat(' - ',DESCRIZION) ) from cimiteri where cimiteri.ID = schede.IDCIMITERO) AS DESCESTESA,	
			paganti.COGNOMENOM ,
			paganti.COMUNE , paganti.TELEFONO ,
			paganti.INDIRIZZO , paganti.CAP
			FROM paganti
			INNER JOIN schede on paganti.ID = schede.IDPAGANTE
			WHERE NOT COGNOMENOM IS NULL
			ORDER BY $sort $direction
            LIMIT $start,$end
			 
		" ; 
		$dt =rs($sql,$_REQUEST);
		
		$sqlCount = "
			SELECT count(*) As total 
            FROM paganti LEFT JOIN schede on paganti.ID = schede.IDPAGANTE
            WHERE NOT COGNOMENOM IS NULL 
			
			
		" ;
		
		$totalFromSession = $_SESSION["SCHEDE_TOTAL"];
		
		if($start==0 || !isset($totalFromSession) ){
			$dtc =rs($sqlCount,$_REQUEST);
			$values = $dtc->getRow();
			$totalFromSession = $values["total"] ;
			$_SESSION["SCHEDE_TOTAL"]=$totalFromSession;
		} 
		
		$idCimitero=$_REQUEST["vc__IDCIMITERO"] ;
		$info="{ cimitero : '$idCimitero' }" ;
		
		exit( recordsetToJson($dt,$totalFromSession,$sql,$info)  );
		
	} else if("$action"=="save"){
		
		$postedData = $_POST["data"]; 
		 
		$data = $json->decode($postedData); 
		$db = db();	
		
		for($i=0;$i<sizeof($data);$i++){
			$record = $data[$i]; 
			
			$Tipo = $db->quoteSmart($record->Tipo)  ;
			$Descrizione = $db->quoteSmart($record->Descrizione)  ;
			
			if( $record->Id >0 ) {
				$sql = "UPDATE $tableName  SET Tipo=$Tipo , Descrizione=$Descrizione where Id=$record->Id" ;			
			}else{
			
			}
			
			$res = $db->query($sql); 
			if(!$res) exit("'Dati non memorizzati a causa di un errore'")	;	
			
		}	
		
		if($i==0) exit("'Nessun dato inviato per il salvataggio'");
		else exit("true");
	}
		
	echo "false";	
	
?>